package zeroj.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import zeroj.web.dispatch.ActionMapping;
import zeroj.web.dispatch.Dispatcher;
import zeroj.web.view.wrapper.HttpRequestWrapper;
import zeroj.web.view.wrapper.HttpResponseWrapper;

/**
 * 
 * 
 * @author lyl(lylsir at gmail dot com)
 *
 * @since
 * 
 * 2008-9-9
 */
public class FilterDispatcher implements Filter {

	private static final Log log = LogFactory.getLog(FilterDispatcher.class);
	
	public static final String ActionPackageName = "action-packages";
	
	private Dispatcher dispatcher;
	
	public void destroy() {

		if(dispatcher != null)
			dispatcher.destroy();
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		HttpRequestWrapper request = new HttpRequestWrapper((HttpServletRequest)req);
		HttpResponseWrapper response = new HttpResponseWrapper((HttpServletResponse)res);
		String uri = ((HttpServletRequest)req).getRequestURI();
		uri = uri.substring(((HttpServletRequest)req).getContextPath().length());
		if(uri.startsWith("/"))
			uri = uri.substring(1);
		if(log.isDebugEnabled())
			log.debug("request uri is " + uri);
		ActionMapping mapping = dispatcher.parseMapping(uri);
		if(mapping == null) {
			if(uri.startsWith(dispatcher.getView().getViewConfig().getTemplatePath()) ||
					("/" + uri).startsWith(dispatcher.getView().getViewConfig().getTemplatePath()))
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
			else
				chain.doFilter(req, res);
		} else {
			dispatcher.service(request, response, mapping);
		}
	}

	public void init(FilterConfig config) throws ServletException {
	
		dispatcher = Dispatcher.get(config);
	}
	
}
